import { defineStore } from "pinia";
import { OrgState } from "@/stores/interface";
import { SysOrg } from "@/api-services/models/system";
import orgApi from "@/api-services/apis/system/orgApi";

const name = "goodAdmin-org";
export const useOrgStore = defineStore({
  id: name,
  state: (): OrgState => ({
    orgTree: [],
    orgSelector: []
  }),
  getters: {
    orgTreeGet: async state => {
      const { getOrgTree } = useOrgStore();
      if (state.orgTree.length === 0) {
        //var orgTreeData=await getOrgTreeApi();
        await getOrgTree();
      }
      return state.orgTree;
    },
    orgSelectorGet: async state => {
      const { getOrgTree } = useOrgStore();
      if (state.orgTree.length === 0) {
        //var orgTreeData=await getOrgTreeApi();
        await getOrgTree();
      }
      return state.orgTree;
    }
  },
  actions: {
    // Set setUserInfo
    setOrgTree(orgTree: SysOrg.OrgSimpleInfo[]) {
      this.orgTree = orgTree;
    },
    async getOrgTree() {
      let res = await orgApi.orgTree();
      this.setOrgTree(res.data.data);
    },
    setOrgSelector(orgSelector: SysOrg.OrgSimpleInfo[]) {
      this.orgSelector = orgSelector;
    },
    async getOrgSelector() {
      let res = await orgApi.orgSelector();
      this.setOrgSelector(res.data.data);
    },
    clearOrgStore() {
      localStorage.removeItem(name);
    }
  }
});
